package com.cmii.sjw.department.control.jsc.util;

import com.cmii.sjw.department.control.jsc.model.entity.Menu;
import com.cmii.sjw.department.control.jsc.model.vo.MenuMeta;
import com.cmii.sjw.department.control.jsc.model.vo.MenuNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单树工具
 * @Author jfh
 * @Date 2025-04-08 周二 14:20
 * @Version 1.0
 */
@Slf4j
public class MenuTreeUtil {

    public static List<MenuNode> buildTree(List<Menu> menus) {

        if (CollectionUtils.isEmpty(menus)) {
            log.warn("构建菜单树时输入菜单列表为空");
            return Collections.emptyList();
        }

        List<MenuNode> tree = new ArrayList<>();
        Map<Long, MenuNode> nodeMap = new HashMap<>();

        // 先处理所有节点
        for (Menu menu : menus) {
            MenuNode node = convertToNode(menu);
            nodeMap.put(node.getId(), node);
        }

        // 构建树结构
        for (MenuNode node : nodeMap.values()) {
            if (StringUtils.isEmpty(node.getParentId())) {
                tree.add(node);
            } else {
                MenuNode parent = nodeMap.get(node.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node);
                }
            }
        }

        // 排序
        sortTree(tree);
        return tree;
    }

    private static MenuNode convertToNode(Menu menu) {
        MenuNode node = new MenuNode();
        node.setId(menu.getId());
        node.setParentId(menu.getParentId());
        node.setName(menu.getName());
        node.setPath(menu.getPath());
        node.setComponent(menu.getComponent());
        node.setRedirect(menu.getRedirect());
        node.setRoute(menu.getRoute());
        node.setSortNo(menu.getSortNo());


        MenuMeta meta = new MenuMeta();
        meta.setTitle(menu.getMetaTitle());
        meta.setSvgIcon(menu.getMetaIcon());
        meta.setComponentName(menu.getMetaComponentName());
        meta.setKeepAlive(menu.getMetaKeepAlive());
        meta.setInternalOrExternal(menu.getMetaInternalOrExternal());
        // 设置 label
        node.setLabel(meta.getTitle());
        node.setMeta(meta);

        return node;
    }

    /**
     * 对菜单树进行排序
     * @param tree 菜单节点列表
     */
    private static void sortTree(List<MenuNode> tree) {
        // 根据sortNo字段对菜单进行排序
        tree.sort(Comparator.comparingInt(MenuNode::getSortNo));
        // 递归排序子菜单
        for (MenuNode node : tree) {
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                sortTree(node.getChildren());
            }
        }
    }
}
